<?php

require "../utility.php";

function addUserToDatabase(mysqli $conn, string $user_name, string $passwd): bool {
    $insert_str = "INSERT INTO User (userName, passwd) VALUES(?, ?);";
    $insert_stmt = $conn->prepare($insert_str);
    $insert_stmt->bind_param("ss", $user_name, $passwd);
    $status = $insert_stmt->execute();
    return $status;
}

$json = getJsonDataFromRawInput();

if (check_keys($json, "user_name", "passwd")) {
    $user_name = $json["user_name"];
    $passwd = $json["passwd"];

    $conn = connect_mysql();

    // 查看是否有重复
    $query_str = "SELECT passwd FROM User WHERE userName = '$user_name';";
    $query = $conn->query($query_str);

    $result = $query->fetch_row();

    // 没有重复就加入数据库
    if (!$result && addUserToDatabase($conn, $user_name, $passwd)) {
        // success
        http_response_code(200);
    } else {
        // failed
        http_response_code(403);
    }

    $query->close();
    $conn->close();
} else {
    // failed
    http_response_code(403);
}

?>